package com.googlecode.garbagecan.jsonstudy.json;

import com.googlecode.garbagecan.jsonstudy.User;
import net.sf.json.JSONObject;

import java.util.Calendar;

public class JSONObjectExample {
	
	public static void main(String[] args) throws Exception {
		test1();
		test2();
		testToBean();
		testFromBean();
	}
	
	private static void test1() {
		String jsonStr ="{"
			+ "username: 'Mandy',"
			+ "password: 'Mandy'"
			+ "}";
		JSONObject jsonObject = (JSONObject)JSONObject.fromObject(jsonStr);
		System.out.println(jsonObject);
		System.out.println(jsonObject.get("username"));
		System.out.println(jsonObject.get("password"));
	}
	
	private static void test2() {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("username", "Mandy");
		jsonObject.put("password", "Mandy");
		jsonObject.put("birthday", Calendar.getInstance().getTime());
		System.out.println(jsonObject.toString());
		System.out.println(jsonObject.get("birthday").getClass());
	}
	
	private static void testToBean() {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("username", "Mandy");
		jsonObject.put("password", "Mandy");
		jsonObject.put("birthday", Calendar.getInstance().getTime());
		
		// net.sf.ezmorph.bean.MorphDynaBean
		System.out.println(JSONObject.toBean(jsonObject).getClass());
		
		User user = (User) JSONObject.toBean(jsonObject, User.class);
		System.out.println(user);
	}
	
	private static void testFromBean() {
		User user = new User();
		user.setUsername("Mandy");
		user.setPassword("Mandy");
		user.setBirthday(Calendar.getInstance().getTime());
		System.out.println(JSONObject.fromObject(user));
	}
}
